﻿using System;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Sunny.UI;
using LogisticsAndong.Comm;
using LogisticsAndong.Model;
using Leeder.Logger;
using System.Collections.Generic;

namespace LogisticsAndong.Forms
{
    public partial class FrmDeviceMonitor :  UIPage
    {

        AutoSizeFormClass asc = new AutoSizeFormClass();

        List<UIPanel> panels = new List<UIPanel>();
        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());
        /// <summary>
        /// 判断窗体是否首次加载
        /// </summary>
        bool isLoad = true;      

        public FrmDeviceMonitor()
        {
            InitializeComponent();
        }

        private void FrmDeviceMonitor_Load(object sender, EventArgs e)
        {
            if (!isLoad)
                return;
            isLoad = false;
            //asc.controllInitializeSize(this.uiTabControl1);

            var systemDevices = GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "OPC" && x.Enabled).ToList();
            systemDevices.ForEach(x =>
            {
                UIPanel uIPanel = new UIPanel() { FillColor = Color.FromArgb(146, 208, 80), Name = x.DeviceCode, Text = x.DeviceName };
                panels.Add(uIPanel);
                flowLayoutPanelIO.Controls.Add(uIPanel);
            });

            foreach(var item in panels)
            {
                item.FillColor = Color.FromArgb(146, 208, 80);
            }
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateUI_DeviceCommunication();
            UpdateUI_IoCommunication();
            UpdateUI_Power(GolbalVariable.UpsStatus);
        }

        /// <summary>
        /// 主要设备通讯监控UI刷新
        /// </summary>
        private void UpdateUI_DeviceCommunication()
        {
            if (this.panelLip.InvokeRequired)
            {
                try
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        UpdateUI();
                    }));
                }
                catch (Exception ex)
                {
                    LogObj.Error(ex.Message);
                }
            }
            else
            {
                UpdateUI();
            }
        }

        /// <summary>
        /// 远程I/O通讯状态UI刷新
        /// </summary>
        private void UpdateUI_IoCommunication()
        {
            //用于判断是否所有设备都正常
            bool isNormalAll = true;
            foreach (var model in GolbalVariable.SystemDeviceBag.Where(x => x.DataSource == "OPC" && x.Enabled))
            {
                UpdateUIDATA(model);
                //当纯在一个或以上设备异常时isNormalAll = false（PLC状态则显示红色）
                if (model.Status == 1)
                    isNormalAll = false;
            }
            //刷新PLC状态显示
            //if (isNormalAll)
            //    buttonplcio.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            //else
            //    buttonplcio.BackColor = Color.Red;
        }

        /// <summary>
        /// 设备电源监控UI刷新
        /// </summary>
        /// <param name="data"></param>
        private void UpdateUI_Power(UpsModel data)
        {
            //绑定ups数据至对应控件
            //if (this.btnUPSPower.InvokeRequired)
            //{
            //    try
            //    {
            //        this.Invoke(new MethodInvoker(() =>
            //        {
            //            BindData(data);
            //        }));
            //    }
            //    catch (Exception ex)
            //    {
            //        LogObj.Error(ex.Message);
            //    }
            //}
            //else
            //    BindData(data);
        }


        private void UpdateUI()
        {
            if (GolbalVariable.LipState)
                this.panelLip.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            else
                this.panelLip.FillColor = Color.Red;
            if (GolbalVariable.PlcState)
                this.panelPlc.FillColor = Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            else
                this.panelPlc.FillColor = Color.Red;
            //if (GolbalVariable.PicsState)
            //    this.panelPics.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            //else
            //    this.panelPics.FillColor = Color.Red;
        }

        /// <summary>
        /// 更新界面数据
        /// </summary>
        private void UpdateUIDATA(SystemDeviceModel systemDevice)
        {
            //try
            //{
            //    var control = this.flowLayoutPanelIO.Controls.Find(systemDevice.DeviceCode, true);
            //    if (control != null)
            //    {
            //        if (control.Length > 0)
            //        {
            //            Button btn = control[0] as Button;
            //            if (systemDevice.Status == 0)
            //                btn.BackColor = Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            //            else
            //                btn.BackColor = Color.Red;
            //        }
            //    }
            //}
            //catch(Exception ex)
            //{
            //    LogObj.Error("IO卡状态更新异常("+ systemDevice.DeviceCode + "):"+ex.Message);
            //}

            foreach (var item in panels)
            {
                if(item.Name == systemDevice.DeviceCode)
                {
                    if (systemDevice.Status == 1)
                        item.FillColor = Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
                    else
                        item.FillColor = Color.Red;
                }
            }
        }

        /// <summary>
        /// 绑定UPS状态数据
        /// </summary>
        /// <param name="model"></param>
        private void BindData(UpsModel model)
        {
            //PLC电源
            //if(GolbalVariable.SystemDeviceBag.Where(x => x.DeviceName == "PLC电源" && x.DataSource == "OPC").FirstOrDefault().Status == 0)
            //{
            //    this.btnplcpower.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            //    this.btnplcpower.Text = "电源电压正常";
            //}else
            //{
            //    this.btnplcpower.BackColor = Color.Red;
            //    this.btnplcpower.Text = "电源电压异常";
            //}
            //UPS电源
            //if (model.State != null && model.QueryResult)
            //{
            //    if (model.State.UpsFault == 0)
            //    {
            //        if (model.State.BatteryVoltage == 1)
            //        {
            //            this.btnUPSPower.BackColor = Color.Red;
            //            this.btnUPSPower.Text = model.State.BatteryVoltageText;
            //        }
            //        else
            //        {
            //            this.btnUPSPower.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(146)))), ((int)(((byte)(208)))), ((int)(((byte)(80)))));
            //            this.btnUPSPower.Text = model.State.BatteryVoltageText;
            //        }
            //    }
            //    else
            //    {
            //        this.btnUPSPower.BackColor = Color.Red;
            //        this.btnUPSPower.Text = model.State.UpsFaultText;
            //    }
            //}
            //else
            //{
            //    this.btnUPSPower.BackColor = Color.Red;
            //    this.btnUPSPower.Text = model.ErrorMsg;
            //}
        }

        private void FrmDeviceMonitor_SizeChanged(object sender, EventArgs e)
        {
            //asc.controlAutoSize(this.uiTabControl1);
        }

        private void FrmDeviceMonitor_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
        }
    }
}
